package LC;

import java.util.Scanner;

/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * (you may want to display this pattern in a fixed font for better legibility)
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:
 * string convert(string text, int nRows);
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 */
public class LC_006_ZigZagConversion {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            int nRows = Integer.parseInt(sc.nextLine());
            System.out.println(convert(s, nRows));
        }
        sc.close();
    }

    private static String convert(String s, int numRows) {
        if (numRows <= 1 || s.length() < 3 || s.length() <= numRows) return s;
        StringBuilder sb = new StringBuilder();
        int zigSpan = numRows * 2 - 2;
        for (int i = 0; i < numRows; i++) {
            for (int j = i; j < s.length(); j += zigSpan) {
                sb.append(s.charAt(j));
                //注意：推导出zigSpan+j-2i的数学公式，一点都不能错
                if (i != 0 && i != numRows - 1 && zigSpan + j - 2 * i < s.length()) {
                    sb.append(s.charAt(zigSpan + j - 2 * i));
                }
            }
        }
        return sb.toString();
    }
}
